# -*- coding: utf-8 -*-

# Create your views here.
import operator

from django.template import RequestContext
from django.shortcuts import render_to_response
from django.http import HttpResponseRedirect

from django.db.models import Q

from ..models import (
    Clientes,
    ItemsRemitos,
    Remitos,
)
from ..forms import (
    BuscarForm,
    RemitoForm,
    ItemsRemitoForm,
)


# REMITOS

def listado_remitos(request):
    """Listado de remitos"""
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = BuscarForm(request.POST)
            if form.is_valid():
                try:
                    text = form.cleaned_data['text']
                    text = str(text)
                    if text:
                        palabras = text.split()
                        cantidad_palabras = len(palabras)
                        fieldnames = ['numeroLinea', 'descripcion']
                        lista_items_encontrados = []
                        for i in range(0, cantidad_palabras):
                            qgroup = reduce(operator.or_,
                                            (Q(**{fieldname + '__icontains': palabras[i]}) for fieldname in fieldnames))
                            lista_temp = ItemsRemitos.objects.filter(qgroup)
                            for item in lista_temp:
                                lista_items_encontrados.append(item)
                            lista_remitos_encontrados = []
                            for item in lista_items_encontrados:
                                if lista_remitos_encontrados.count(item.remito) == 0:
                                    lista_remitos_encontrados.append(item.remito)
                    else:
                        lista_remitos_encontrados = Remitos.objects.all()
                    variables = RequestContext(request, {'todo': lista_remitos_encontrados, 'form': form})
                    return render_to_response('listado_remitos.html', variables)
                except:
                    return HttpResponseRedirect('/')
            else:
                lista_remitos_encontrados = Remitos.objects.all()
                variables = RequestContext(request, {'todo': lista_remitos_encontrados, 'form': form})
                return render_to_response('listado_remitos.html', variables)
        else:
            form = BuscarForm()
            todo = Remitos.objects.all()
            variables = RequestContext(request, {'form': form, 'todo': todo})
            return render_to_response('listado_remitos.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def agregar_remitos(request):
    """Agregar remito nuevo"""
    if request.user.is_authenticated():
        if request.method == 'POST':
            form = RemitoForm(request.POST)
            if form.is_valid():
                registro = form.save()
                return HttpResponseRedirect('/remitos/listado/items/%s/' % (registro.id))
        else:
            form = RemitoForm()
        variables = RequestContext(request, {
            'form': form,
        })
        return render_to_response('agregar_remitos.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def editar_remitos(request, remitoid):
    """Edita remito"""
    if request.user.is_authenticated():
        r = Remitos.objects.get(pk=remitoid)
        if request.method == 'POST':
            form = RemitoForm(request.POST, instance=r)
            if form.is_valid():
                registro = form.save()
                return HttpResponseRedirect('/remitos/listado/')
        else:
            form = RemitoForm(instance=r)
        variables = RequestContext(request, {
            'form': form,
            'remito': r,
        })
        return render_to_response('editar_remitos.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def listado_items_remitos(request, remitoid):
    """Listado de items del remito"""
    if request.user.is_authenticated():
        remito = Remitos.objects.get(pk=remitoid)
        if request.method == 'POST':
            form = ItemsRemitoForm(request.POST)
            if form.is_valid():
                registro = form.save()
                registro.remito = remito
                registro.save()
                return HttpResponseRedirect('/remitos/listado/items/%s/' % (remitoid))
        else:
            form = ItemsRemitoForm()
        todo = ItemsRemitos.objects.filter(remito=remito)
        variables = RequestContext(request, {
            'form': form,
            'todo': todo,
            'remito': remito,
        })
        return render_to_response('listado_itemsRemitos.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def listado_items_remitos_cliente(request, clienteid):
    """Listado de items del remito"""
    if request.user.is_authenticated():
        cliente = Clientes.objects.get(pk=clienteid)
        todo = ItemsRemitos.objects.filter(remito__cliente=cliente)
        variables = RequestContext(request, {
            'todo': todo,
            'cliente': cliente,
        })
        return render_to_response('listado_itemsRemitos_cliente.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def editar_items_remitos(request, itemid):
    """Edita items del remito"""
    if request.user.is_authenticated():
        r = ItemsRemitos.objects.get(pk=itemid)
        if request.method == 'POST':
            form = ItemsRemitoForm(request.POST, instance=r)
            if form.is_valid():
                registro = form.save()
                return HttpResponseRedirect('/remitos/listado/items/%s/' % r.remito.id)
        else:
            form = ItemsRemitoForm(instance=r)
        variables = RequestContext(request, {
            'form': form,
            'itemRemito': r,
        })
        return render_to_response('editar_itemsRemitos.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def check_items_remitos(request, itemid):
    """Confirmar antes de eliminar"""
    if request.user.is_authenticated():
        item = ItemsRemitos.objects.get(pk=itemid)
        variables = RequestContext(request, {'item': item})
        return render_to_response('borrado_itemsRemitos.html', variables)
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)


def borrar_items_remitos(request, itemid):
    """Elimina Banco dolares"""
    if request.user.is_authenticated():
        r = ItemsRemitos.objects.get(pk=itemid)
        cliente = r.cliente
        fecha = r.fecha
        numeroRemito = r.numeroRemito
        r.delete()
        return HttpResponseRedirect('/remitos/listado/items/%s/%s/%s/' % (cliente.id, fecha, numeroRemito))
    else:
        return HttpResponseRedirect('/login/?next=%s' % request.path)
